import Vue from "vue";
import VueRouter from "vue-router";
import routes from "./route";
import NProgress from "nprogress";
import "nprogress/nprogress.css";
import store from "@/store";

Vue.use(VueRouter);

//重写push方法
const oldPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (
  location,
  onComplete = () => {},
  onAbort = () => {}
) {
  oldPush.call(this, location, onComplete, onAbort);
};
//重写replace方法
const oldReplace = VueRouter.prototype.replace;
VueRouter.prototype.push = function (
  location,
  onComplete = () => {},
  onAbort = () => {}
) {
  oldReplace.call(this, location, onComplete, onAbort);
};

const router = new VueRouter({
  mode: "history",
  routes,
});
//有token 有用户信息 放行
//有token 无用户信息 请求用户信息 请求不到用户信息则清除token 跳转到login重新登录
//无token 判断当前要去的路由的元信息 是否需要权限  若需要权限则跳转到登录  不需要权限则放行
router.beforeEach(async (to, from, next) => {
  NProgress.start(); //loading加载条
  const token = store.state.user.token;
  const nickName = store.state.user.userInfo.nickName; //代表用户信息(有nickname就一定有用户信息)

  //有token
  if (token) {
    //先判断当前去的地方是不是login 若已有token则不需要登录,直接跳转到home
    if (to.name === "Login") {
      next("/home");
      if (from.name === "Home") NProgress.done();
    }
    //判断有无用户信息
    if (nickName) {
        //有则放行
        next();
    } else {
      try {
        //没有则请求用户信息
        await store.dispatch("user/getUserInfo");
        next();
      } catch (e) {
        //请求不到 则清除token 重新登录
        store.commit("user/clear_Token");
        next(`/login?to=${to.name}`);
      }
    }
  } else {
    //没有token
    //判断当前要去的地方需不需要权限
    if (to.meta.isAuth) {
      next(`/login?to=${to.name}`);
    } else {
      next();
    }
  }
});
router.afterEach(() => {
  NProgress.done();
});
export default router;
